// fire_alarm_alert_controller.dart
import 'package:get/get.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:rjpb/page/home/controllers/home_controller.dart';
import 'package:rjpb/page/home/fireAlarm/controller/fireAlarm_page_controller.dart';

class FireAlarmAlertController extends GetxController {
  final RxBool _isShowing = false.obs;
  final RxString _alertMessage = ''.obs;
  final RxList<Map<String, dynamic>> _alarmList = <Map<String, dynamic>>[].obs;

  final AudioPlayer _audioPlayer = AudioPlayer();
  bool _isAudioPlaying = false;

  bool get isShowing => _isShowing.value;
  String get alertMessage => _alertMessage.value;
  List<Map<String, dynamic>> get alarmList => _alarmList;

  @override
  void onClose() {
    _audioPlayer.dispose();
    super.onClose();
  }

  // 显示火警弹窗
  Future<void> showAlert(
      String message, List<Map<String, dynamic>> alarms) async {
    if (_isShowing.value) return;

    _alertMessage.value = message;

    print("火警弹窗消息：$alarms");

    _alarmList.assignAll(alarms);
    _isShowing.value = true;

    // 播放警报音
    await _playAlarmSound();
  }

  // 隐藏弹窗
  Future<void> dismissAlert() async {
    if (!_isShowing.value) return;

    await _stopAlarmSound();
    _isShowing.value = false;
  }

  // 播放警报音
  Future<void> _playAlarmSound() async {
    if (_isAudioPlaying) return;

    try {
      _isAudioPlaying = true;
      await _audioPlayer.play(AssetSource('audio/fire.mp3'),
          mode: PlayerMode.lowLatency);
      _audioPlayer.onPlayerComplete.listen((_) {
        _isAudioPlaying = false;
        if (_isShowing.value) {
          _playAlarmSound(); // 循环播放
        }
      });
    } catch (e) {
      print('播放警报音失败: $e');
      _isAudioPlaying = false;
    }
  }

  // 停止警报音
  Future<void> _stopAlarmSound() async {
    if (!_isAudioPlaying) return;

    try {
      await _audioPlayer.stop();
      _isAudioPlaying = false;
    } catch (e) {
      print('停止警报音失败: $e');
    }
  }

  // 消音按钮
  Future<void> muteAlarm() async {
    await _stopAlarmSound();
  }

  // 查看详情按钮
  void viewDetails() async {
    print("查看详情按钮被点击了！${_alarmList}");

    // final alarms =
    //     _alarmList.where((alarm) => alarm['isRealtime'] == 1).toList();
    // print("过滤后的火警信息：$alarms");
    // if (alarms.isEmpty) {
    //   Get.snackbar('提示', '没有找到有效的火警信息');
    //   return;
    // }

    // final firstAlarm = alarms.first;
    // print("过滤后的火警信息：$firstAlarm");
    await dismissAlert();

    // 切换到火警页面
    final homeController = Get.find<HomeController>();
    homeController.changePage(1);

    // 手动跳转到火警页面
    homeController.pageController.animateToPage(
      1,
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
    // 等待页面加载完成后触发第一条数据卡片的点击事件
    Future.delayed(Duration(milliseconds: 500), () async {
      final fireAlarmController = Get.find<FireAlarmPageController>();
      await fireAlarmController.triggerFirstCardTapWithLoading();
    });
  }
}
